package cn.webwheel.whtml;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Collection;
import java.util.Map;

public class ModelSelectDlg extends JDialog implements ActionListener {

    public String selected;

    private JTextArea label = new JTextArea();
    private JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));

    public ModelSelectDlg(String path, Map<String, Object> params, Collection<String> models) {

        setModal(true);
        setTitle("模型选择（" + path + "）");
        setAlwaysOnTop(true);
        setIconImage(MainFrame.icon2);

        StringBuilder sb = new StringBuilder(path);
        if (!params.isEmpty()) {
            sb.append('?');
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() instanceof String[]) {
                    for (String v : (String[]) entry.getValue()) {
                        sb.append(entry.getKey());
                        sb.append('=');
                        sb.append(v);
                        sb.append('&');
                    }
                } else {
                    sb.append(entry.getKey());
                    sb.append("=File[");
                    sb.append(((File[]) entry.getValue()).length);
                    sb.append("]&");
                }
            }
            sb.setLength(sb.length() - 1);
        }

        for (String model : models) {
            JButton bt = new JButton(model);
            panel.add(bt);
            bt.addActionListener(this);
        }

        add(panel, BorderLayout.SOUTH);
        label.setLineWrap(true);
        label.setWrapStyleWord(true);
        label.setEditable(false);
        add(label, BorderLayout.CENTER);

        ((JPanel) getContentPane()).registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

        setMinimumSize(new Dimension(300, 20));
        pack();
        int h1 = label.getPreferredSize().height;
        String s = sb.toString();
        label.setToolTipText(s);
        if (s.length() > 256) s = s.substring(0, 256);
        label.setText(s);
        int h2 = label.getPreferredSize().height;
        setSize(new Dimension(getWidth(), getHeight() + h2 - h1));
        setLocationRelativeTo(null);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        selected = e.getActionCommand();
        dispose();
    }
}
